<template>
	<view class="page">
        <!-- 公共组件-每个页面必须引入 -->
        <public-module></public-module>
			<!--view class=" u-m-l-20 u-m-r-20 u-m-t-20" v-if="cart_take.orderType == 'takecheck'">
				<view class="base-panel-box">
					<view class="item_single">购买成功后二维码券将自动发送在您的订单中</view>
				</view>
			</view-->
	<!--view class="u-error-dark-bg u-padding-30">小程序审核合规性测试中，请勿下单</view-->
	<view class="header">
		<view class="orderType">
			<view class="dinein" :class="{active: cart_type.orderType_take == 'in'}" @tap="setOrdertype('in')">
				<text>自提自取</text>
			</view>
			<view class="takeout" :class="{active: cart_type.orderType_take == 'out'}" @tap="setOrdertype('out')">
				<text>闪电配送</text>
			</view>
		</view>
	</view>
			
		<view class="u-m-b-20 " style="position: relative;">
			<view v-if="cart_type.orderType_take == 'in'">
				<view class="u-padding-30 u-text-center selectstore"  @click="showAddressPoP=true">{{current_in_storeName}}</view>
				<u-action-sheet
					:show="showAddressPoP"
					:actions="shopAddressList"
					title="请选择分店"
					@close="showAddressPoP = false"
					@select="addressSelect">
				</u-action-sheet>
			</view>
			<view v-else>
			<view class="item_single empty u-padding-30" v-if="userInfo.token">
				<navigator url="/pagesPackageA/address/address?source=1">
						<view v-if="address_is_empty === true">{{$t('selectaddress')}}</view>
						<view v-else>{{$t('deliveryto')}}:{{ addressData.region_fullname+' '+addressData.address }}</view>
					  <view class="u-flex u-flex-between" style="border-radius: 20px;background: #ffcc00;padding:6px 20px;border: sienna dotted 1px;" v-if="total_shipping_fee > 0">
							<view class="u-flex-10">此区域需额外补快递费：</view>
							<view class="u-flex-2 price u-text-right"><span class="price fuhao">{{symbol}} </span>{{ parseFloat(total_shipping_fee).toFixed(2) }}</view>
					  </view>
				</navigator>
			</view>
			<view v-else class="dddd u-padding-30">
				请先登陆
			</view>
			<image class="a-bg" src=""></image>
			</view>
		</view>

	<!-- 列表 -->
		
		<u-empty :text="$t('goodsnodata')" mode="car" icon="https://i.yodin.com/storage/empty/nocart.png" v-if="cartStorage.length===0"></u-empty>
		<view  v-if="loadstatus">
			<view class="cart-list">
			<view v-if="cartStorage.length>0" v-for="(shop,index) in cartgGroupedData">
				<view class="shop u-flex u-flex-between u-p-t-20 u-p-l-20 u-p-r-20">
					<view>{{shop.groupname}}</view>
				</view>
				<view class="cart-item" v-for="(goods,key) in shop.list">
					<view class="image-wrappers" @tap="$tools.goJump('/pages/goods/view',{id:goods.goods_id})">
						<u--image :showLoading="true" :src="goods.cover_url==''?'https://zy.tzzs.com/storage/no_image.jpg':goods.cover_url" width="100%" height="auto" mode="widthFix" radius="12rpx">
							<template v-slot:loading><u-loading-icon ></u-loading-icon></template>
						</u--image>
					</view>
					<view class="item-right">
						<text class="ctitle u-m-b-20" @tap="$tools.goJump('/pages/goods/view',{id:goods.goods_id})">{{goods.goods_name}}</text>
						<view v-if="goods.sku_name">{{goods.sku_name}}</view>
						<view class="u-flex u-flex-between">
							<view>
								<span class="price fuhao">{{symbol}}</span>
								<span class="price">{{goods.price}}</span>
							</view>
							<view class="btn-group">
								<button type="default" v-show="goodCartNum(goods.goods_id,goods.sku_id)" plain class="btn reduce_btn"
								 size="mini" hover-class="none" @tap="handleReduceFromCart(goods)">
									<u-icon name="minus" labelPos="bottom"></u-icon>
								</button>
								<view class="number" v-show="goodCartNum(goods.goods_id,goods.sku_id)">{{ goodCartNum(goods.goods_id,goods.sku_id) }}</view>
								<button type="primary" class="btn add_btn" size="min" hover-class="none" 
								 :style="[{background:'#666666'}]"
								 v-if="goodCartNum(goods.goods_id,goods.sku_id)>0&&goods.goods_type==1">
									<u-icon name="plus" labelPos="bottom" color="color['u-bg-color']"></u-icon>
								</button>
								<button type="primary" class="btn add_btn" size="min" hover-class="none" v-else
									@tap="handleAddToCart(goods,1)" >
									<u-icon name="plus" labelPos="bottom" color="color['u-bg-color']"></u-icon>
								</button>
							</view>
						</view>
						
					</view>
				</view>
			  <view class="u-flex u-flex-between u-margin-20" v-if="cart_type.orderType_take == 'out'&&shopinfo.delivery_cost > 0">
					<view class="u-flex-10">包装费</view>
					<view class="u-flex-2 price u-text-right"><span class="price fuhao">{{symbol}} </span>{{parseFloat(shopinfo.packing_fee).toFixed(2)}}</view>
			  </view>
			  <view class="u-flex u-flex-between u-margin-20" v-if="cart_type.orderType_take == 'out'&&shopinfo.delivery_cost > 0">
					<view class="u-flex-10">配送费</view>
					<view class="u-flex-2 price u-text-right"><span class="price fuhao">{{symbol}} </span>{{ parseFloat(shopinfo.delivery_cost).toFixed(2) }}</view>
			  </view>
			  <view class="u-flex u-flex-between u-margin-20" v-if="cart_type.orderType_take == 'out'&&shopinfo.delivery_cost > 0">
					<view class="u-flex-10">{{$t('expressfee')}}</view>
					<view class="u-flex-2 price u-text-right"><span class="price fuhao">{{symbol}} </span>{{parseFloat(shipping_fee*1).toFixed(2)}}</view>
			  </view>

			  
			</view>
			
			<view v-if="cartStorage.length===0">
                <view class="u-font-32 u-font-bold u-padding-20 u-m-t-20">热门推荐</view>
				<goods-row :list="recommendGoods"></goods-row>
			</view>
			<u-gap height="70"></u-gap>
		</view> 
		<!-- 底部菜单栏 -->
    <view class="action-section">
		<view class="u-line-1 pay-alert">
			<u-icon name="info-circle" :label="$t('successfulPaymentOrder')" color="#2d8cf0" size="12" labelSize="12" labelColor=""></u-icon>
		</view>
		<view class="actionbox ">
			<view class="u-flex u-flex-between u-p-t-20">
				<view class="u-flex-9 u-flex u-flex-between">
				  <view class="">
					{{ $t("totalcost") }}:
					<span class="price fuhao">{{symbol}}</span>
					<span class="price">{{(totalamount).toFixed(2)}}</span>
				  </view>
				</view>
				<view class="u-flex-3">
					<button type="primary" shape="circle" class="confirm-btn" :disabled="btnstatus" :loading="btnstatus" loadingText="save.." @click="createOrder">
						确定
					</button>
				</view>
			</view>
		<view :style="{height: systemInfo.titleBarHeight+'rpx'}"></view>
		</view>
    </view>

		</view>

	</view>
</template>

<script>

import { mapState, mapMutations } from 'vuex';
import base from '@/config/baseUrl.js';
import { api_goods_list,api_user_addresslist,api_order_save,api_assets_paymentaccount } from '@/config/api.js';
import goodsRow from "./module/goods-row";
import fTabbar from '@/components/module/f-tabbar/f-tabbar';
import { hidePageNavInWechatBrowser,isWechat } from '@/config/h5Utils';
export default {
  components: {
	  goodsRow,fTabbar
    },
    data() {
        return {
			systemInfo:base.systemInfo,
			loadstatus:false,
			btnstatus:false,
			height:'60px',
			cartStorage:[],
			cartgGroupedData:[],//按shopid重组的购物车
			address_is_empty:true,
			addressData: [],
			recommendGoods:[],//购物车为空时的推荐商品
			shipping_fee:0,
			total_shipping_fee:0,
			totalamount:0,
			addr_id:'',
			ee:'',
			shopinfo:[],
			site_info:{
				money:{
					
				}
			},
			cart_type:{
				orderType_take:'in',
			},
			symbol:'',
			showAddressPoP:false,
			shopAddressList:[],
			current_in_storeID:'',
			current_in_storeName:'',
        }
    },
  watch: {
    //显示空白页
    addressData(e) {
      let empty = e == undefined || e.length <= 0 ? true : false;
      if (this.address_is_empty !== empty) {
        this.address_is_empty = empty;
      }
	  if (empty == false){
		    this.shipping_fee=e.shipping_fee
			this.addr_id=e.addr_id
			this.rest_buildcartGroup()
	  }
    },
  },
	computed:{
	    ...mapState(['PrimaryColor','extConfig','userInfo','siteInfo']),
		
			goodCartNum() {	//计算单个商品添加到购物车的数量
				return (id,skuid) => this.cartStorage.reduce((acc, cur) => {
						if(cur.id === id&&cur.sku_id === skuid) {
							return acc += cur.num
						}
						return acc
					}, 0)
			},
	},

	onReady() {
		if (isWechat()){
			this.height = '90px'
		}
		hidePageNavInWechatBrowser();
	},
    async onLoad(e) {
		this.site_info=uni.getStorageSync('siteInfo');
		this.symbol=this.site_info.money.symbol

		uni.setNavigationBarTitle({title: '选择配送方式'});
		this.getDefaultAddress()
		// if (e.state=='buy'){
		// 	this.cart = uni.getStorageSync('buy')
		// 	this.ee=e.state
		// }
		this.get_paymentaccount()
		
		this.shopinfo = uni.getStorageSync('shopInfo')
		console.log('thisshopinfo',this.shopinfo)
		this.shopAddressList=this.shopinfo.addressList.map(item =>({
			name:item.address,
			store_addr_id:item.addr_id,
		}))

		if (uni.getStorageSync('cart_type').length===0){
			
		}else{
			this.cart_type = uni.getStorageSync('cart_type')
		}
        if (uni.getStorageSync('current_in_storeID').length===0){
            this.shopinfo.addressList.forEach(( item,i) => {
                if (i == 0){
					this.current_in_storeName=item.address
					this.current_in_storeID=item.addr_id
					uni.setStorageSync('current_in_storeID',this.current_in_storeID)
					uni.setStorageSync('current_in_storeName',this.current_in_storeName)
				}
            });
        }else{
			this.current_in_storeID=uni.getStorageSync('current_in_storeID')
			this.current_in_storeName=uni.getStorageSync('current_in_storeName')
		}


    },
	onShow(){
		this.totalamount=0
		this.total_shipping_fee=0

		this.cartStorage = uni.getStorageSync('cartStorage')
			this.rest_buildcartGroup()
			this.recommend()
			console.log(this.cartgGroupedData)
		},
	onPullDownRefresh() {
		this.cartStorage = uni.getStorageSync('cartStorage')
		this.rest_buildcartGroup()
		this.recommend()
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 100);
	},
    methods: {
		OpenAddressPoP(){
			this.showAddressPoP = true;uni.hideKeyboard();
		},
		addressSelect(e){
			this.current_in_storeName=e.name
			this.current_in_storeID=e.store_addr_id
			uni.setStorageSync('current_in_storeID',this.current_in_storeID)
			uni.setStorageSync('current_in_storeName',this.current_in_storeName)
		},
		setOrdertype(type){
			this.cart_type={
				orderType_take:type,
			}
			uni.setStorageSync('cart_type',this.cart_type)
			this.rest_buildcartGroup()
		},
		
		get_paymentaccount() {
			//this.coininfo=this.siteInfo.money
			//return;
			// api_assets_paymentaccount({}).then((res) => {
			// 	this.coininfo=res
			// }).catch((e) => {});
		},
		createOrder(){
        	this.judgeLogin(() => {
				this.btnstatus=true
				api_order_save({
					cartgGroupedData:JSON.stringify(this.cartgGroupedData),
					addr_id:this.addr_id,
					coinTypeid:this.site_info.money.coinid,
					current_in_storeID:this.shopinfo.current_in_storeID,
					current_in_store_tableID:'',
				}).then((res) => {
					this.btnstatus=false
					uni.setStorageSync('cartStorage', [])
					this.$tools.goJump('/pagesPackageA/order/pay',{order_code:res.order_code},'','launch')
				}).catch((error) => {this.btnstatus=false});
			});
		},
		getDefaultAddress(){
			api_user_addresslist({
				find_users_id:this.userInfo.member_id
			}).then((res) => {
					this.loadstatus=true  //为加载siteInfo而延时，否则刷新js出错
					res.roomlist.forEach((addr,index) => {
						if (this.address_is_empty==true){
						   this.addressData=addr
						   this.address_is_empty = false; 
						}
					    if (addr.is_default==1){
						   this.addressData=addr
						   this.address_is_empty = false; 
					    }
					})
			}).catch((error) => {});
		},
		recommend(){
			if (this.cartStorage.length<=1){
				api_goods_list({
				  page:1,
				  limit:6,
				  search_field:'is_hot',
				  search_exp:'=',
				  search_value:'1',
				  thumb_width:300,
				  thumb_height:300
				}).then((res) => {
				  this.recommendGoods=res.list
				}).catch((error) => {});
			}
		},
		//购物车按 shopid分组
		rest_buildcartGroup(){
			const cart_count = Object.keys(this.cartStorage).length
			if (cart_count==0){return}
			this.totalamount = 0
			this.cartgGroupedData = this.cartStorage.reduce( (acc, cur) => {
				  let key
				  if (cur.group_id==''){
					key='g'
				  }else{
					key=cur.group_id
				  }
				  if (!acc[key]) acc[key] = {}
				  if (!acc[key]['list']) acc[key]['list'] = []
					acc[key].groupname=cur.group_name==''?'':cur.group_name
					acc[key].group_id = cur.group_id
					acc[key].list.push(cur)
					this.totalamount+=parseFloat(cur.price)*parseFloat(cur.num)
				  return acc
				}, {})
				this.total_shipping_fee=0
			    for (let [k, v] of Object.entries(this.cartgGroupedData)) {
					this.total_shipping_fee+=parseFloat(this.shipping_fee)
			    }
				this.totalamount+=this.total_shipping_fee
				console.log('this.cartgGroupedData',this.cartgGroupedData)
		},
		handleReduceFromCart( good) {
			const cart_count = Object.keys(this.cartStorage).length
			if (cart_count==0){return}
				const index = this.cartStorage.findIndex(item => {
						if(good.sku_id>0) {
							return (item.id === parseFloat(good.goods_id)) && (item.sku_id === good.sku_id)
						} else {
							return item.id === parseFloat(good.goods_id)
						}
				})
				this.cartStorage[index].num -= 1
				if(this.cartStorage[index].num <= 0) {
					this.cartStorage.splice(index, 1)
				}
				uni.setStorageSync('cartStorage', this.cartStorage)
				this.rest_buildcartGroup()
		},
		handleAddToCart(good, num) {	//添加到购物车
			const cart_count = Object.keys(this.cartStorage).length
			if (cart_count==0){return}
					const index = this.cartStorage.findIndex(item => {
						if(good.sku_id>0) {
							return (item.id === parseFloat(good.goods_id)) && (item.sku_id === good.sku_id)
						} else {
							return item.id === parseFloat(good.goods_id)
						}
					})
					if(index > -1) {
						this.cartStorage[index].num += num
					}
					uni.setStorageSync('cartStorage', this.cartStorage)
					this.rest_buildcartGroup()
		},
    },
}
</script>

<style lang='scss'>
	/deep/.uni-page-body{
		background: #fff;
	}
	@import '~@/pages/goods/module/shop.scss';
	
	/*地址分割线*/
  .a-bg {
    position: absolute;
    left: 0;
    bottom: 0;
    display: block;
    width: 100%;
    height: 5upx;
  }

  
	.header {
		width: 100%;
		padding: 20rpx;
		background-color: #ffffff;
		border-bottom:solid 1px #f5f5f5;
		text-align: center;
		height: 90rpx;
  		.orderType {
			width: 50%;
			margin: auto;
  			background-color: #eeeeee;
  			border-radius: 38rpx;
  			display: flex;
  			align-items: center;
  			font-size: 24rpx;
  			padding: 0 38rpx;
  			color:#000000;
  			.dinein, .takeout {
  				text-align:center;
  				&.active {
  					padding: 14rpx 38rpx;
  					color: #ffffff;
  					background-color: #5ac725;
  					border-radius: 38rpx;
  				}
  			}
  			.takeout {margin-left: 38rpx;height: 100%;flex: 1;}			
  			.dinein.active {margin-left: -38rpx;}
  			.takeout.active {margin-right: -38rpx;}
  		}
	}
	/* 购物车列表项 */
	.cart-item {
		display: flex;
		position: relative;
		padding: 30upx 40upx;
		border-bottom: #e8e8e8 solid 1px;

		.image-wrappers { 
			width: 180upx !important;
			height: 180upx !important;
			flex-shrink: 0;
			position: relative;

			img { 
				width: 230upx !important;
				height: 230upx !important;
				border-radius: 8upx;
			}
		} 

		.checkbox {
			position: absolute;
			left: -16upx;
			top: -16upx;
			z-index: 8;
			font-size: 44upx;
			line-height: 1;
			padding: 14upx;
			background: #fff;
			border-radius: 50px;
		}

		.item-right {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: hidden;
			position: relative;
			padding-left: 30upx;
			.ctitle,.price {
				line-height: 40upx;
				font-weight: bolder;
			}

			.attr {
				height: 50upx;
				line-height: 50upx;
			}

			.price {
				height: 50upx;
				line-height: 50upx;
			}
		}
	}
</style>

